
package com.netease.xone.fragment;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.meta.User;
import Utils.XoneUtil;
import android.app.Service;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.netease.pkgRelated.XoneConsts.BUNDLE_KEY;
import com.netease.pkgRelated.XoneConsts.INPUT_CELLPHONE_TYPE;
import com.netease.xone.R;
import com.netease.xone.app.XoneApp;
import com.netease.xone.widget.CustomDialog.OnCustomDlgCancelListener;

public class FragCellPhoneNickAndPw extends FragCellPhoneBase {

    private int mAction;
    private String mPhoneNum;
    private String mCaptcha;
    private int mTitleResId;

    private EditText mEditNickname;
    private TextView mTvNicknameTip;
    private EditText mEditPassword;
    private EditText mEditPasswordRepeat;
    private TextView mSubmit;
    private LinearLayout mLayNicknameBlock;

    private FragmentManager mFragmentManager;

    private int mTransactionId;

    public static final int REGISTER_SUCCESS = 1;
    public static final int REGISTER_NICKNAME_DUPLICATED = 2;
    public static final int VERIFYCODE_ERROR = 3;
    public static final int REGISTER_OCCUPIED = 4;
    public static final int SERVER_ERROR = 5;
    public static final int UNKOWN_ERROR = 6;
    public static final int RESET_PASSWORD_SUCCESS = 7;
    public static final int RESET_PASSWORD_ACCOUNT_NOT_EXIST = 8;

    public static FragCellPhoneNickAndPw newInstance(int type, String phonenum, String captcha) {
        FragCellPhoneNickAndPw fragment = new FragCellPhoneNickAndPw();
        Bundle b = new Bundle();
        b.putInt(BUNDLE_KEY.CELLPHONE_TYPE, type);
        b.putString(BUNDLE_KEY.CELLPHONE_NUMBER, phonenum);
        b.putString(BUNDLE_KEY.CELLPHONE_CAPTCHA, captcha);
        fragment.setArguments(b);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        if (bundle != null && bundle.containsKey(BUNDLE_KEY.CELLPHONE_TYPE)
                && bundle.containsKey(BUNDLE_KEY.CELLPHONE_NUMBER)
                && bundle.containsKey(BUNDLE_KEY.CELLPHONE_CAPTCHA)) {
            mAction = bundle.getInt(BUNDLE_KEY.CELLPHONE_TYPE);
            mPhoneNum = bundle.getString(BUNDLE_KEY.CELLPHONE_NUMBER);
            mCaptcha = bundle.getString(BUNDLE_KEY.CELLPHONE_CAPTCHA);
        }
        if (mAction == INPUT_CELLPHONE_TYPE.Register) {
            mTitleResId = R.string.cellphoneRegister;
        } else {
            mTitleResId = R.string.findPassword;
        }
        getActivity().setTitle(mTitleResId);
        mFragmentManager = getFragmentManager();
        View view = inflater.inflate(R.layout.fragment_nickandpw, container, false);
        mTvNicknameTip = (TextView)view.findViewById(R.id.verifyNicknameTip);
        mEditNickname = (EditText)view.findViewById(R.id.verifyNicknameInput);
        mEditNickname.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                String nickname = s.toString().trim();
//                checkNickname(nickname);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
//                    mTvNicknameTip.setVisibility(View.GONE);
                    return;
                }
                int len = 0;
                for (int i = 0; i < s.length(); i++) {
                    String ss = Character.toString(s.charAt(i));
                    if (ss.matches("[\\u4E00-\\u9FA5]")) {
                        len += 2;
                    } else {
                        len++;
                    }
                    if (len > getActivity().getResources().getInteger(R.integer.nicknameMaxLen)) {
                        String sss = s.subSequence(0, i).toString();
                        mEditNickname.setText(sss);
                        mEditNickname.setSelection(sss.length());
                        break;
                    }
                }
//                String nicknameStr = mEditNickname.getText().toString().trim();
//                checkNickname(nicknameStr);
            }
        });
        mEditPassword = (EditText)view.findViewById(R.id.verifyPasswordInput);
        mEditPasswordRepeat = (EditText)view.findViewById(R.id.verifyPasswordRepeat);
        mLayNicknameBlock = (LinearLayout)view.findViewById(R.id.verifyNicknameBlock);
        if (mAction == INPUT_CELLPHONE_TYPE.Register) {
            mLayNicknameBlock.setVisibility(View.VISIBLE);
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    if (getActivity() != null) {
                        InputMethodManager imm = (InputMethodManager)XoneApp.getAppInstance()
                                .getSystemService(Service.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(mEditNickname, 0);
                    }
                }
            }, 300);
            mEditNickname.requestFocus();
        } else if (mAction == INPUT_CELLPHONE_TYPE.FindPw) {
            mLayNicknameBlock.setVisibility(View.GONE);
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    if (getActivity() != null) {
                        InputMethodManager imm = (InputMethodManager)XoneApp.getAppInstance()
                                .getSystemService(Service.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(mEditPassword, 0);
                    }
                }
            }, 300);
            mEditPassword.requestFocus();
        }
        mSubmit = (TextView)view.findViewById(R.id.Submit);
        mSubmit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                doDone();
            }
        });
        return view;
    }

    private void checkNickname(String nickname) {
        int resid = -1;
        mTvNicknameTip.setVisibility(View.GONE);
        if (XoneUtil.getNicknameLen(nickname) < getActivity().getResources().getInteger(
                R.integer.nicknameMinLen)) {
            resid = R.string.nicknameLenUnreachFour;
        } else if (XoneUtil.getNicknameLen(nickname) > getActivity().getResources().getInteger(
                R.integer.nicknameMaxLen)) {
            resid = R.string.nicknameLenOverCeiling;
        } else if (XoneUtil.isNicknameContainsSpecialChar(nickname)) {
            resid = R.string.nicknameContainsSpecialChar;
        }
        if (resid >= 0) {
            mTvNicknameTip.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icn_whatsup, 0, 0, 0);
            mTvNicknameTip.setText(resid);
            mTvNicknameTip.setVisibility(View.VISIBLE);
            return;
        }
    }

//    @Override
//    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//        menu.add(0, MENU_ID.menu_cellphone_complete, 0, getActivity().getText(R.string.complete))
//                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//        super.onCreateOptionsMenu(menu, inflater);
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        if (item.getItemId() == MENU_ID.menu_cellphone_complete) {
//            doDone();
//        }
//
//        return super.onOptionsItemSelected(item);
//    }

    private void doDone() {
        if (mAction == INPUT_CELLPHONE_TYPE.Register) {
            int msgid = -1;
            String nicknameStr = mEditNickname.getText().toString().trim();
            String passwordStr = mEditPassword.getText().toString().trim();
//            String pwRepeat = mEditPasswordRepeat.getText().toString().trim();
            if (TextUtils.isEmpty(nicknameStr)) {
                msgid = R.string.inputNicknamePrompt;
            }  else if (XoneUtil.getNicknameLen(nicknameStr) < getActivity().getResources()
                    .getInteger(R.integer.nicknameMinLen)) {
                msgid = R.string.nicknameLenUnreachFour;
            } else if (XoneUtil.getNicknameLen(nicknameStr) > getActivity().getResources()
                    .getInteger(R.integer.nicknameMaxLen)) {
                msgid = R.string.nicknameLenOverCeiling;
            } else if (XoneUtil.isNicknameContainsSpecialChar(nicknameStr)) {
                msgid = R.string.nicknameContainsSpecialChar;
            } else if (TextUtils.isEmpty(passwordStr)) {
                msgid = R.string.inputPasswordPrompt;
            }else if (passwordStr.length() < 6) {
                msgid = R.string.passwordLenUnreachSix;
            } /*else if (!passwordStr.equals(pwRepeat)) {
                msgid = R.string.pwinconformity;
            }*/
            if (msgid >= 0) {
                showToast(msgid);
                return;
            }
            doReg(nicknameStr, passwordStr);
        } else if (mAction == INPUT_CELLPHONE_TYPE.FindPw) {
            int msgid = -1;
            String passwordStr = mEditPassword.getText().toString().trim();
//            String pwRepeat = mEditPasswordRepeat.getText().toString().trim();
            if (TextUtils.isEmpty(passwordStr)) {
                msgid = R.string.inputPasswordPrompt;
            } else if (passwordStr.length() < 6) {
                msgid = R.string.passwordLenUnreachSix;
            } /*else if (!passwordStr.equals(pwRepeat)) {
                msgid = R.string.pwinconformity;
            }*/
            if (msgid >= 0) {
                showToast(msgid);
                return;
            }
            doModifyPw(passwordStr);
        }
    }

    private void doReg(String nickName, String pw) {
//        showWatting(getString(R.string.registering));
        showCustomDialog(getActivity(), getString(R.string.registering), mOnCustomDlgCancelListener);
        XoneService.getInstance().addListener(mXoneCallBack);
        mTransactionId = XoneService.getInstance()
                .doCellPhoneReg(mPhoneNum, nickName, mCaptcha, pw);

    }

    private void doModifyPw(String pw) {
//        showWatting(getString(R.string.resetPasswording));
        showCustomDialog(getActivity(), getString(R.string.resetPasswording), mOnCustomDlgCancelListener);
        XoneService.getInstance().addListener(mXoneCallBack);
        mTransactionId = XoneService.getInstance()
                .doModifyCellPhonPw(mPhoneNum, mCaptcha, pw);
    }
    private OnCustomDlgCancelListener mOnCustomDlgCancelListener = new OnCustomDlgCancelListener(){

        @Override
        public void onCancel() {
            XoneService.getInstance().cancelTransaction(mTransactionId);
        }  
    };
    @Override
    public void onDestroy() {
        super.onDestroy();
        XoneService.getInstance().removeListener(mXoneCallBack);
    }
    @Override
    protected void onLeftTopBack() {
        getFragmentManager().popBackStack();
    }
    private XoneCallBack mXoneCallBack = new XoneCallBack() {

        @Override
        public void onLogin(int transactionId, User account) {
//            stopWaiting();
            closeCustomDialog();
            XoneService.getInstance().removeListener(mXoneCallBack);
            getActivity().finish();
        }

        @Override
        public void onLoginError(int transactionId, int errCode, String err) {
            if (mTransactionId == transactionId) {
//                stopWaiting();
                closeCustomDialog();
                showToast(err);
                XoneService.getInstance().removeListener(mXoneCallBack);
            }
        }

        @Override
        public void onModifyCellPhonePw(int transactionId) {
//            stopWaiting();
            closeCustomDialog();
            showToast(R.string.resetPasswordSuccess);
            XoneService.getInstance().removeListener(mXoneCallBack);
            getFragmentManager().popBackStack();
        };

        @Override
        public void onModifyCellPhonePwError(int transactionId, int errCode, String err) {
            if (mTransactionId == transactionId) {
//                stopWaiting();
                closeCustomDialog();
                showToast(err);
                XoneService.getInstance().removeListener(mXoneCallBack);
            }
        };
    };
}
